#!/usr/bin/env python3
"""诊断 find_related_concepts 功能"""

import asyncio
import sys
import os
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from src.config import load_config
from src.database.manager import DatabaseManager
from src.core.conversation_manager import ConversationManager

async def diagnose_find_related_concepts():
    """诊断 find_related_concepts 功能"""
    print("=== 诊断 find_related_concepts 功能 ===")
    
    try:
        # 加载配置
        config = load_config()
        print("✓ 配置加载成功")
        
        # 初始化数据库管理器
        db_manager = DatabaseManager(config)
        await db_manager.initialize()
        print("✓ 数据库管理器初始化成功")
        
        # 检查Neo4j连接
        neo4j_client = db_manager.neo4j_client
        if await neo4j_client.ping():
            print("✓ Neo4j连接正常")
        else:
            print("✗ Neo4j连接失败")
            return
        
        # 获取Neo4j统计信息
        stats = await neo4j_client.get_graph_statistics()
        print(f"Neo4j统计: {stats}")
        
        # 检查是否有Concept节点
        concept_query = "MATCH (c:Concept) RETURN count(c) as concept_count, collect(c.concept_id)[0..5] as sample_ids"
        concept_result = await neo4j_client.execute_query(concept_query)
        if concept_result:
            concept_count = concept_result[0]['concept_count']
            sample_ids = concept_result[0]['sample_ids']
            print(f"Concept节点数量: {concept_count}")
            print(f"示例Concept ID: {sample_ids}")
            
            if concept_count > 0 and sample_ids:
                # 测试find_related_concepts方法
                test_concept_id = sample_ids[0]
                print(f"\n测试find_related_concepts，使用concept_id: {test_concept_id}")
                
                related_concepts = await neo4j_client.find_related_concepts(test_concept_id)
                print(f"find_related_concepts结果: {related_concepts}")
                
                # 检查该概念的关系
                relation_query = """
                MATCH (c:Concept {concept_id: $concept_id})
                OPTIONAL MATCH (c)-[r]-(other)
                RETURN c.name as concept_name, 
                       count(r) as total_relations,
                       collect(DISTINCT type(r)) as relation_types,
                       collect(DISTINCT labels(other)) as connected_node_types
                """
                relation_result = await neo4j_client.execute_query(relation_query, {'concept_id': test_concept_id})
                if relation_result:
                    rel_info = relation_result[0]
                    print(f"概念关系信息: {rel_info}")
            else:
                print("没有可用的Concept节点进行测试")
        else:
            print("无法获取Concept节点信息")
        
        # 测试ConversationManager的find_related_concepts
        print("\n=== 测试ConversationManager.find_related_concepts ===")
        conversation_manager = ConversationManager(db_manager, config)
        
        # 使用一个测试概念ID
        test_concept = "test_concept"
        cm_result = await conversation_manager.find_related_concepts(test_concept)
        print(f"ConversationManager.find_related_concepts结果: {cm_result}")
        
    except Exception as e:
        print(f"诊断过程中发生错误: {e}")
        import traceback
        traceback.print_exc()
    
    finally:
        # 关闭数据库连接
        if 'db_manager' in locals():
            await db_manager.close()
            print("\n数据库连接已关闭")

if __name__ == "__main__":
    asyncio.run(diagnose_find_related_concepts())